var t = getApp()
Page({
  data: {
    ency: '',
    iv: '',
    errMsg: '',
    tel:'',
    new_tel:'',
    navHeight:t.globalData.navHeight,
    title:'绑定手机号',
  },
  onLoad: function (options) {
    this.get_tel()
  },
  onRefresh(){
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading(); 
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    this.get_tel()
  },
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.onRefresh();
    setTimeout(function () {
      // 不加这个方法真机下拉会一直处于刷新状态，无法复位
      wx.stopPullDownRefresh()
    }, 1000)
  },
  get_tel(e){
    var that = this
    t.request('/users/my_phone',{phone:''},function(e){
      console.log(e);
      if (e.code==200) {
        that.setData({
          tel:e.result
        })
      }
    })
  },
  getPhoneNumber (e) {
    console.log(e.detail);
    var that = this
    var ency = e.detail.encryptedData;
    var iv = e.detail.iv;
    var errMsg = e.detail.errMsg
    if (iv == null || ency == null) {
      wx.showToast({
        title: "授权失败,请重新授权！",
        icon: 'none',
      })
      return false
    }
    wx.showLoading({
      title: '请稍后',
    })
    wx.checkSession({
      success: (res) => {
        wx.login({
          success(e){
            t.request('/users/get_session',{code: e.code,
            iv:iv,da:ency},function(event){
              if (event.code==200) {
                wx.hideLoading({
                  success: (res) => {},
                })
                console.log(event.result.phoneNumber);
                that.setData({
                  tel:event.result.phoneNumber,
                })
              }
            })
          }
        })
        console.log(res)
      },
    })
    that.setData({
      ency: ency,
      iv: iv,
      errMsg: errMsg
    })
  },
  change_tel(e){
    console.log();
    this.setData({
      new_tel:e.detail.value
    })
  },
  confirmTel(e){
    var tel = this.data.new_tel?this.data.new_tel:''
    if (tel=='') {
      wx.navigateBack({
        delta: 0,
      })
    }else{
      if(!(/^1[3456789]\d{9}$/.test(tel))){ 
        wx.showToast({
          title: '请输入正确的手机号',
          icon:'none'
        })   
        return;
      }
      t.request('/users/my_phone',{phone:tel},function(e){
        console.log(e);
        if (e.code==200) {
          wx.showToast({
            title: '修改成功',
          })
          wx.navigateBack({
            delta: 0,
          })
        }
      })
    }
  }
})